<template>
	<view class="container">
		<view class="carousel">
			<swiper indicator-dots circular=true duration="400">
				<swiper-item class="swiper-item" v-for="(item,index) in imgList" :key="index">
					<view class="image-wrapper">
						<image :src="item" class="loaded" mode="aspectFill"></image>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="introduce-section">
			<view class="price-box">
				<view>
					<!-- <text class="price" v-if="detail.goodsType == 1">
						<text class="iconfont icon-youhuijuan" style="font-size: 40upx;padding-right:20upx ;"></text>
						<text>{{specList[0].coupons || 0}}</text>
					</text> -->
					<text class="price">￥{{specList[0].price || 0}}</text>
				</view>
				<text class="stock">销量：{{detail.sales || 0}}件</text>
			</view>
			<view class="title">{{detail.goodsName}}</view>
			<!--  分享 -->
			<!-- <view class="share-section" @tap="shareFc()">
				<image src="../../static/img/share.png" mode="" style="width: 22upx;height: 22upx;"></image>
				<view class="share-btn">
					分享
				</view>
			</view> -->
		</view>


		<view class="c-list">
			<!-- <view class="c-row b-b" @click="toPage(0,'/pages/shop/shopDetail/shopDetail?id=')">
				<image src="../../static/img/EAB.png" mode="" class="tit"></image>
				<view class="con-list">
					<text class="title">{{detail.merchantName}}</text>
					<view class="intr">{{detail.merchantName}}</view>
					<view class="phone" @click.stop="callPhone">
						<text>{{detail.merchantPhone}}</text>
						<image src="../../static/img/phoneCall.png" mode="" class="phonecall"></image>
					</view>
				</view>
				<view class="right iconfont icon-fanhui"></view>
			</view> -->
			<!-- <view class="c-row a-b" style="margin-top: 20upx;">
				<view class="top">
					<view class="talk-left">
						宝贝评价(90)
					</view>
					<view class="talk-right" @click.stop.prevent="toPage(0,'/pages/allComment/allComment')">
						<text>查看全部</text>
						<view class="talkIcon iconfont icon-fanhui"></view>
					</view>
				</view>
				<view class="talkContent">
					<view class="content_top">
						<image src="../../static/img/salesman.png" mode=""></image>
						<text>奶酪踢足球</text>
					</view>
					<view class="text">
						他家衣服买了好几件了，便宜质量又好，性价比超高的！
					</view>
				</view>

			</view> -->
		</view>


		<view class="detail-desc">
			<view class="d-header">
				<text>图文详情</text>
			</view>
			<image v-for="item in desc" :src="item" mode="widthFix" style="width: 100%;"></image>
		</view>
		<!-- 底部操作菜单 -->
		<view class="page-bottom">
			<view class="left">
				<!-- <view class="shop" @click="toPage(0,'/pages/shop/shopDetail/shopDetail?id=')">
					<image src="../../static/img/home.png" mode="" class="img"></image>
					<view>店铺</view>
				</view> -->
				<!-- <view class="shoucang" @click="Mycollect">
					<image src="../../static/img/collect.png" mode="" class="img" v-if="favorite"></image>
					<image src="../../static/img/xingzhuang60kaobei2.png" class="img" v-else></image>
					<view>gouwuch</view>
				</view> -->
				<view class="shoucang" @click="toPage(3,'/pages/buyCar/index')">
					<u-badge type="error" size="mini" count="7" :is-center="true"></u-badge>
					<image src="../../static/img/navbar/room-query2.png" mode="" class="img"></image>
					<view>购物车</view>
				</view>
				<!-- <view class="shoucang" @click="toPage(0,'/pages/notice/chat?name=客服娜娜')">
					<image src="../../static/img/icon_serveic.png" mode="" class="img"></image>
					<view>客服</view>
				</view> -->
			</view>
			<view class="action-btn-group">
				<button type="primary" class=" action-btn  buy-now" @click="toggleSpec(0)">加入购物车</button>
				<button type="primary" class=" action-btn  add-cart" @click="toggleSpec(1)">立即购买</button>
			</view>
		</view>


		<!-- 规格-模态层弹窗 -->
		<view class="popup spec" :class="specClass" @touchmove.stop.prevent="stopPrevent" @click="toggleSpec">
			<!-- 遮罩层 -->
			<view class="mask"></view>
			<view class="layer attr-content" @click.stop="stopPrevent">
				<image src="../../static/img/quxiao@2x.png" mode="" class="close" @click="toggleSpec"></image>
				<view class="a-t">
					<image :src="specSelected[0].goodsSpecsImg"></image>
					<view class="right">
						<view class="selected">
							价格：
							<text class="price">¥{{specSelected[0].price}}</text>
						</view>
						<text>库存 {{specSelected[0].stock}} 件</text>
						<view class="selected">
							规格：
							<text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">
								{{sItem.goodsSpecsName}}
							</text>
						</view>
					</view>
				</view>
				<view class="attr-list">
					<text>规格：</text>
					<view class="item-list">
						<text v-for="(childItem, childIndex) in specList"  :key="childIndex" class="tit"
						 :class="{selected: childItem.selected}" @click="selectSpec(childIndex, childItem.goodsSpecsId)">
							{{childItem.goodsSpecsName}}
						</text>
					</view>
				</view>

				<view class="count">
					<view>数量</view>
					<!-- <u-number-box v-model="num" :min="1" :max='specSelected[0].stock'></u-number-box> -->
						<view class="number">
							<view class="sub" @tap.stop="sub">
								<view class="icon jian"></view>
							</view>
							<view class="input">
								<input type="number" v-model="num" @blur="discard"/>
							</view>
							<view class="add"  @tap.stop="add">
								<view class="icon jia"></view>
							</view>
						</view>
				</view>

				<button class="btn" @click="buy">确定</button>
			</view>
		</view>
		<!-- 分享 -->
		<share ref="share" :contentHeight="580" :shareList="shareList"></share>
		<!-- 图片展示由自己实现 -->
		<view class="flex_row_c_c modalView" v-show='qrShow' :class="qrShow?'show':''" @tap="hideQr()">
			<view class="flex_column">
				<view class="backgroundColor-white padding1vh border_radius_10px">
					<image :src="poster.finalPath || ''" mode="widthFix" class="posterImage"></image>
				</view>
				<view class="flex_row marginTop2vh">
					<button class="flex_btn" size="mini" @tap.prevent.stop="saveImage()">保存图片</button>
					<button class="flex_btn" size="mini" @tap.prevent.stop="share()">分享图片</button>
				</view>
			</view>
		</view>
		<!-- 画布 -->
		<view class="hideCanvasView">
			<canvas class="hideCanvas" canvas-id="default_PosterCanvasId" :style="{width: (poster.width||10) + 'px', height: (poster.height||10) + 'px'}"></canvas>
		</view>
	</view>
</template>

<script>
	import share from '@/components/share/share';
	import _app from '@/util/QS-SharePoster/app.js';
	import uniNumberBox from "@/components/uni-number-box/uni-number-box.vue"
	import {goodsDetail,addCartGoods} from '../../api/goods/index'
	import {getSharePoster} from '@/util/QS-SharePoster/QS-SharePoster.js';
	export default {
		components: {
			share,
			uniNumberBox
		},
		data() {
			return {
				goodsType:null,
				goodsId:null,
				detail:{},
				poster: {},
				qrShow: false,
				canvasId: 'default_PosterCanvasId',
				openType:0,
				num:1,
				specClass: 'none',
				specSelected: [],
				type:0,
				price:0,
				favorite: true,
				shareList: [{
					"type": 1,
					"icon": "/static/img/share_wechat.png",
					"text": "微信好友"
				}, {
					"type": 2,
					"icon": "/static/img/share_moment.png",
					"text": "朋友圈"
				}, {
					"type": 3,
					"icon": "/static/img/share_qq.png",
					"text": "QQ好友"
				}, {
					"type": 4,
					"icon": "/static/img/share_qqzone.png",
					"text": "QQ空间"
				}],
				imgList: [],
				desc:[],
				specList:[]
			};
		},
		onLoad(options) {
			this.goodsType = options.goodsType
			this.goodsId = options.goodsId;
			this.type = options.type;
			this.getDetail();
		},
		methods: {
			//减少数量
			sub(){
				if(this.num<=1){
					return;
				}
				this.num--;
			},
			//增加数量
			add(){
				if(this.num >= this.specSelected[0].stock){
					return;
				}
				this.num++;
			},
			discard(){
				if(this.num >= this.specSelected[0].stock){
					uni.showToast({
						title:'库存不足',
						icon:'none'
					})
					this.num = this.specSelected[0].stock
				}else if(this.num == '' || this.num == 0){
					this.num = 1
				}
			},
			getDetail(){
					goodsDetail({goodsId:this.goodsId}).then(res=>{
						this.detail = res.data.obj
						this.imgList = JSON.parse(res.data.obj.coverImg)
						this.desc = JSON.parse(res.data.obj.detailsImgs)
						this.specList = res.data.obj.goodsSpecsList
						this.specSelected.push(this.specList[0]);
						this.$set(this.specList[0], 'selected', true);
					}).catch(err=>{
					})
			},
			// 打电话
			callPhone() {
				uni.makePhoneCall({
				    phoneNumber: '114' //仅为示例
				});
			},
			//规格弹窗开关
			toggleSpec(type) {
				this.openType = type;
				if (this.specClass === 'show') {
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
				} else if (this.specClass === 'none') {
					this.specClass = 'show';
				}
			},
			//选择规格
			selectSpec(index, pid) {
				let list = this.specList;
				list.forEach(item => {
						this.$set(item, 'selected', false);
				})

				this.$set(list[index], 'selected', true);
				//存储已选择
				/**
				 * 修复选择规格存储错误
				 * 将这几行代码替换即可
				 * 选择的规格存放在specSelected中
				 */
				this.specSelected = [];
					this.specSelected.push(list[index]);
			},
			//分享
			share() {
				this.$refs.share.toggleMask();
			},

			//收藏
			Mycollect() {
				if(this.favorite) {
					uni.showToast({
					    title: '收藏成功',
					    duration: 2000,
						success:()=>{
							this.favorite = false;
						}
					});
				}else{
					uni.showToast({
					    title: '取消收藏成功',
					    duration: 2000,
						success:()=>{
							this.favorite =true;
						}
					});
				}
			},
			async buy() {
				if(this.openType == 0){
					try {
						let params = {
							areaId:this.detail.areaId,
							goodsId:this.goodsId,
							goodsSpecsId:this.specSelected[0].goodsSpecsId,
							quantity:this.num
						}
						await addCartGoods(params);
						uni.showToast({
						    title: '加入购物车成功',
							icon:'none',
						    duration: 2000,
							success:()=>{
								this.specClass = 'hide';
								setTimeout(() => {
									this.specClass = 'none';
								}, 250);
							}
						});
					}catch(error) {

					}
				}else{
					this.specClass = 'hide';
					setTimeout(() => {
						this.specClass = 'none';
					}, 250);
					let goodsList=[]
					let orderDetail = {}
					let shopDetail={}
					let meassage = {}
					let goodsData =[]
					orderDetail.image = this.imgList[0]
					orderDetail.goodsName = this.detail.goodsName
					orderDetail.price = this.specSelected[0].price
					orderDetail.coupons = this.specSelected[0].coupons
					orderDetail.specName = this.specSelected[0].goodsSpecsName
					orderDetail.goodsType = this.goodsType;
					orderDetail.num = this.num
					goodsList.push(orderDetail)
					shopDetail.shopName = this.detail.merchantName
					shopDetail.image = this.imgList[0]

					meassage.shopDetail = shopDetail
					meassage.goodsList = goodsList
					goodsData.push(meassage)

					uni.setStorageSync("goodsData",goodsData)
					if(this.goodsType == 1) {
						uni.navigateTo({
							url: '/pages/order/createOrder?goodsId='+ this.goodsId+'&goodsSpecsId='+ this.specSelected[0].goodsSpecsId +'&goodsType='+ this.goodsType+'&orderType=1'+ '&price='+ this.specSelected[0].coupons*this.num +'&number='+this.num
						})
					}else{
						uni.navigateTo({
							url: '/pages/order/createOrder?goodsId='+ this.goodsId+'&goodsSpecsId='+ this.specSelected[0].goodsSpecsId +'&goodsType='+ this.goodsType+'&orderType=1'+ '&price='+ this.specSelected[0].basePrice*this.num+'&number='+this.num
						})
					}
				}

			},
			stopPrevent() {},
			async shareFc() {
				try {
					_app.log('准备生成:' + new Date())
					const d = await getSharePoster({
						_this: this, //若在组件中使用 必传
						type: 'testShareType',
						formData: {
							//访问接口获取背景图携带自定义数据

						},
						posterCanvasId: this.canvasId, //canvasId
						delayTimeScale: 20, //延时系数
						background: {
							width: 750,
							height: 1334,
							backgroundColor: '#FFFFFF'
						},
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							const dx = bgObj.width * 0.3;
							const fontSize = bgObj.width * 0.045;
							const lineHeight = bgObj.height * 0.04;
							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([{
										type: 'image',
										url: this.imgList[0],
										dWidth: bgObj.width,
										dHeight: bgObj.width,
										dx: 0,
										dy: 0,
									},
									{
										type: 'text',
										text: this.detail.goodsName,
										size: 35,
										color: 'black',
										alpha: 1,
										textAlign: 'left',
										textBaseline: 'middle',
										dx: 20,
										dy: bgObj.width + 60,
										lineFeed: {
											maxWidth: bgObj.width - 40,
											lineHeight: 50,
											lineNum: 2
										},

									},
									{
										type: 'text',
										text: '￥'+this.specList[0].basePrice,
										size: 45,
										color: 'red',
										alpha: 1,
										textAlign: 'left',
										textBaseline: 'middle',
										dx: 20,
										dy: bgObj.width + 200,
									},
									// {
									// 	type: 'text',
									// 	text: '赠送',
									// 	size: 35,
									// 	color: '#7B8D31',
									// 	alpha: 1,
									// 	textAlign: 'left',
									// 	textBaseline: 'middle',
									// 	dx: 640,
									// 	dy: bgObj.width + 200,
									// },


									{
										type: 'qrcode',
										text: '你好，我是取舍',
										size: bgObj.width * 0.3,
										dx: 20,
										dy: bgObj.height - 30 - bgObj.width * 0.3
									},
									{
										type: 'image',
										url: 'https://gd3.alicdn.com/imgextra/i4/479184430/O1CN01nCpuLc1iaz4bcSN17_!!479184430.jpg_400x400.jpg',
										size: fontSize,
										dWidth: bgObj.width * 0.2,
										dHeight: bgObj.width * 0.2,
										dx: 580,
										dy: bgObj.height - 30 - bgObj.width * 0.2
									},
									{
										type: 'text',
										text: '长按图片',
										size: 35,
										color: '#949494',
										alpha: 1,
										textAlign: 'left',
										textBaseline: 'middle',
										dx: 280,
										dy: 1220,
									},
									{
										type: 'text',
										text: '识别二维码',
										size: 35,
										color: '#949494',
										alpha: 1,
										textAlign: 'left',
										textBaseline: 'middle',
										dx: 280,
										dy: 1290,
									},
								]);
							})
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => { // 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					_app.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath)
					this.poster.finalPath = d.poster.tempFilePath;
					this.qrShow = true;
				} catch (e) {
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
				}
			},
			saveImage() {
				// #ifndef H5
				uni.saveImageToPhotosAlbum({
					filePath: this.poster.finalPath,
					success(res) {
						_app.showToast('保存成功');
					}
				})
				// #endif
				// #ifdef H5
				_app.showToast('保存了');
				// #endif
			},
			share() {
				// #ifdef APP-PLUS
				_app.getShare(false, false, 2, '', '', '', this.poster.finalPath, false, false);
				// #endif

				// #ifndef APP-PLUS
				_app.showToast('分享了');
				// #endif
			},
			hideQr() {
				this.qrShow = false;
			}
		},
	}
</script>

<style lang='scss'>
	@import './index.scss';
</style>